﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using RabbitMQ.Client;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Distributed.RedisSession.Controllers
{
    /// <summary>
    /// https://www.cnblogs.com/frank-zhang/p/13523926.html
    /// 创建容器并运行（15672是管理界面的端口，5672是服务的端口。这里顺便将管理系统的用户名和密码设置为admin admin）
    /// docker pull rabbitmq:3.7.28-management
    /// docker run -d --hostname rabbitmq --name rabbitmq -e RABBITMQ_DEFAULT_USER=admin -e RABBITMQ_DEFAULT_PASS=admin -e RABBITMQ_DEFAULT_VHOST=my_vhost -p 15672:15672 -p 5672:5672 rabbitmq:3.7.28-management
    /// </summary>
    public class RabbitmqController : Controller
    {
        private readonly ILogger<RabbitmqController> _logger;
        private IConfiguration configuration;
        private IRabbitMQTest channel;

        //dotnet Distributed.RedisSession.dll --urls=http://*:5010 --ip=127.0.0.1 --port=5010
        //dotnet Distributed.RedisSession.dll --urls=http://*:5011 --ip=127.0.0.1 --port=5011
        public RabbitmqController(ILogger<RabbitmqController> logger, IConfiguration configuration, IRabbitMQTest channel, IDistributedCache distributedCache, IMemoryCache memoryCach)
        {
            _logger = logger;
            this.configuration = configuration;
            this.channel = channel;
        }


        //http://localhost:5010/Rabbitmq/index/16
        public IActionResult Index(int number)
        {
            base.ViewBag.BrowserUrl = $"{base.Request.Scheme}://{base.Request.Host.Host}:{base.Request.Host.Port}";
            base.ViewBag.AppUrl = $"{base.Request.Scheme}://{base.Request.Host.Host}:{configuration["port"]}";
            base.ViewBag.TotalCount += 1;

          

            Console.WriteLine("准备就绪，开始写入");
            if (number < 1) number = 16;
            for (int i = 0; i < number; i++)
            {
                string msg = $"Task-{configuration["port"]}->{i}";
                channel.Send(msg);               
            }
            
            return View();
        }


        public IActionResult Receive(string queue)
        {
            if (string.IsNullOrEmpty(queue)) queue = "Queue_Order";
            base.ViewBag.BrowserUrl = $"{base.Request.Scheme}://{base.Request.Host.Host}:{base.Request.Host.Port}";
            base.ViewBag.AppUrl = $"{base.Request.Scheme}://{base.Request.Host.Host}:{configuration["port"]}";
            base.ViewBag.TotalCount += 1;



            channel.Receive(queue);

            return View();
        }
    }
}
